<template>
  <div id="layout">
    <br />
    <br />
    <br />

    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="姓名">
        <el-input
          v-model="form.userName"
          placeholder="请填写真实姓名"
        ></el-input>
      </el-form-item>

      <el-form-item label="性别">
        <el-radio-group v-model="form.userSex">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
          <el-radio label="保密"></el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="职位">
        <el-input
          v-model="form.userJob"
          placeholder="请填写真实职位"
        ></el-input>
      </el-form-item>

      <el-form-item label="证件号码">
        <el-input v-model="form.userNumber" placeholder="身份证号码"></el-input>
      </el-form-item>

      <el-form-item label="手机号码">
        <el-input
          v-model="form.userPhone"
          placeholder="请输入常用手机号码"
        ></el-input>
      </el-form-item>

      <el-form-item label="QQ号码">
        <el-input
          v-model="form.userQQ"
          placeholder="请输入常用QQ号码"
        ></el-input>
      </el-form-item>

      <el-form-item label="上传人脸" style="display: table-cell">
        <el-upload
          ref="upload"
          list-type="picture"
          style="display: inline-block"
          action=""
          accept=".jpg, .jpeg, .png"
          :limit="1"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="getFile"
        >
          <el-button>选择人脸图片</el-button>
        </el-upload>

        <el-button
          @click="getCompetence"
          style="vertical-align: top; margin-left: 5px"
          >打开摄像头拍摄</el-button
        >
      </el-form-item>

      <el-tag
        :key="tag"
        v-if="isshow"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
        style="margin-left: 80px; margin-top: 5px"
      >
        <i class="el-icon-success"></i>
        {{ tag }}
      </el-tag>

      <el-form-item style="margin-top: 20px">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 遮罩层 -->
    <transition name="el-fade-in-linear">
      <div id="custom_mask" v-show="show3" @click="stopNavigator"></div>
    </transition>

    <!-- 摄像头 -->
    <el-collapse-transition>
      <div id="camera" v-show="show3" @click.stop>
        <!-- 摄像头 我要用的摄像头存放位置 -->

        <el-alert
          title="请拍摄人物的正脸！！！"
          type="warning"
          show-icon
          :closable="false"
        >
        </el-alert>
        <video
          id="videoCamera"
          :width="videoWidth"
          :height="videoHeight"
          v-if="!img"
          autoplay
        ></video>
        <canvas
          id="canvas"
          :width="videoWidth"
          :height="videoHeight"
          v-show="img"
        ></canvas>

        <br /><br />
        <el-button style="margin-left: 120px" @click="takePhoto"
          >拍照</el-button
        >
        <el-button style="margin-left: 30px" :disabled="!img" @click="determine"
          >确认使用</el-button
        >
        <el-button style="margin-left: 30px" @click="stopNavigator"
          >取消</el-button
        >
      </div>
    </el-collapse-transition>
  </div>
</template>

<script>
import request from "../../utils/request";
export default {
  data() {
    return {
      form: {
        userId: "",
        userName: "",
        userJob: "",
        userSex: "",
        userNumber: "",
        userPhone: "",
        userQQ: "",
        userFaceFeature: "",
        // 有人动我代码
      },
      tag: "",
      isshow: false,
      show3: false,
      videoWidth: 340,
      videoHeight: 340,
      thisVideo: null,
      img: false,
    };
  },
  methods: {
    // 提交函数
    onSubmit() {
      if (
        this.form.userName !== "" &&
        this.form.userJob !== "" &&
        this.form.userSex !== "" &&
        this.form.userNumber !== "" &&
        this.form.userPhone !== "" &&
        this.form.userQQ !== ""
      ) {
        if (this.form.userFaceFeature !== "") {
          if (this.form.userId !== "") {
            // 发送注册请求
            request
              .post("/user/addFace", this.form)
              .then((res) => {
                if (res.code === "200") {
                  // 跳转首页
                  sessionStorage["user"] = JSON.stringify(res.data);
                  this.loaddata();
                  this.$message({
                    message: "更改成功",
                    type: "success",
                  });
                } else {
                  this.$message.error(res.message);
                }
              })
              .catch((res) => {
                this.$message.error("网络错误，请稍后重试");
              });
          } else {
            this.$message.error("非法用户,请先登录");
          }
        }else{
          this.$message.error("请选择人脸！！！");
        }
      } else {
        this.$message.error("还有信息没填写完整!!!");
      }
    },

    // 取消函数
    cancel() {
      this.$router.push("/");
    },

    // 删除选择的文件
    handleClose(_) {
      // 隐藏图标
      this.isshow = false;
      // 清除数据
      this.$refs["upload"].clearFiles();
      this.form.userFaceFeature = "";
      this.$message({
        message: "删除已选择图片成功",
        type: "warning",
      });
    },

    // 选择图片后触发的函数
    getFile(file) {
      //显示图标
      this.tag = file.name;
      this.isshow = true;

      // 进行编码数据绑定，
      this.getBase64(file.raw).then((res) => {
        if (res.length > 0) {
          this.form.userFaceFeature = res;
        }
      });
    },

    // 获取图片转base64，工具方法
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },

    // 摄像头开启函数
    getCompetence() {
      // 开启遮罩层
      this.show3 = true;

      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");

      this.thisVideo = document.getElementById("videoCamera");

      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象

      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }

      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象

      // 使用getUserMedia，因为它会覆盖现有的属性。

      // 这里，如果缺少getUserMedia属性，就添加它。

      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)

          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;

          // 有些浏览器不支持，会返回错误信息

          // 保持接口一致

          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }

          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia

          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }

      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };

      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject

          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。

            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }

          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 关闭摄像头
    stopNavigator() {
      // 关闭遮罩层
      this.show3 = false;
      this.img = false;
      this.thisVideo.srcObject.getTracks()[0].stop();
    },

    // 拍照
    takePhoto() {
      this.img = true;
      //获得Canvas对象
      const video = document.getElementById("videoCamera");
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      ctx.drawImage(video, 0, 0, 340, 340);

      // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
      let img = document.getElementById("canvas").toDataURL();

      this.form.userFaceFeature = img;

      this.thisVideo.srcObject.getTracks()[0].stop();
    },

    // 确认使用方法
    determine() {
      this.show3 = false;
      this.img = false;
      this.tag = "摄像头拍照人脸.png";
      this.isshow = true;
      this.$message({
        message: "选择成功",
        type: "success",
      });
    },

    loaddata() {
      // 初次创建组件时，从本地缓存中，加载数据
      let user = JSON.parse(sessionStorage.getItem("user"));
      this.form.userId = user.userId;
      this.form.userName = user.userName;
      this.form.userJob = user.userJob;
      this.form.userSex = user.userSex;
      this.form.userNumber = user.userNumber;
      this.form.userPhone = user.userPhone;
      this.form.userQQ = user.userQq;
    },
  },
  mounted() {
    this.loaddata();
  },
};
</script>

<style lang="less" scoped>
#layout {
  height: 400px;
  width: 650px;

  margin: 60px auto;
}

#select {
  margin-top: 5px;
  height: 20px;
  margin-left: 80px;
}

#camera {
  height: 500px;
  width: 540px;
  background: rgb(255, 255, 255);
  margin: 0 auto;
  z-index: 10;
  border-radius: 8px;
  position: fixed;
  left: 32%;
  top: 0px;
}

#custom_mask {
  position: fixed;
  left: 0px;
  top: 0px;
  background: rgba(31, 31, 31, 0.51);
  height: 100%;
  width: 100%;
}
#videoCamera {
  border: #3c97bf 1px solid;
  border-radius: 60%;
  margin-left: 100px;
  margin-top: 30px;
  /* 翻转摄像头  */
  -moz-transform: scaleX(-1);
  -webkit-transform: scaleX(-1);
  -o-transform: scaleX(-1);
  transform: scaleX(-1);
  /*IE*/
  filter: FlipH;
}

#canvas {
  border: #3c97bf 1px solid;
  border-radius: 60%;
  margin-left: 100px;
  margin-top: 30px;
  /* 翻转摄像头  */
  -moz-transform: scaleX(-1);
  -webkit-transform: scaleX(-1);
  -o-transform: scaleX(-1);
  transform: scaleX(-1);
  /*IE*/
  filter: FlipH;
}
</style>